package com.daipresents.gfmon;

import java.lang.management.ManagementFactory;
import org.apache.log4j.Logger;
import java.lang.management.OperatingSystemMXBean;

public class OSMonitor implements OSMonitorMBean {
    
    private static final String SUCCESS = "success";
    
    private Logger logger = Logger.getLogger(OSMonitor.class);
    private boolean isSunBean = false;
    private OperatingSystemMXBean bean;
    private com.sun.management.OperatingSystemMXBean sunBean;
    private long totalPhysicalMemorySize;
    private long totalSwapSpaceSize;
    
    public OSMonitor() {
        super();
        logger.debug(OSMonitor.class.getName() + "Constractor Called.");
        
        bean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        
        //SunのJVMの場合は拡張されたOperatingSystemMXBeanが使える。
        if (bean instanceof com.sun.management.OperatingSystemMXBean){
            sunBean = 
                (com.sun.management.OperatingSystemMXBean) bean;
            totalPhysicalMemorySize = sunBean.getTotalPhysicalMemorySize();
            totalSwapSpaceSize = sunBean.getTotalSwapSpaceSize();
            isSunBean = true;
        }
    }
    
    @Override
    public String getLogging(){
        String message = 
            String.format("ProcessCpuTime:%s,FreePhysicalMemoryInPercent:%s,FreeSwapSpaceSizeInPercent:%s,SystemLoadAverage:%s",
                    getProcessCpuTime(),
                    getFreePhysicalMemoryInPercent(),
                    getFreeSwapSpaceSizeInPercent(),
                    getSystemLoadAverage());
        logger.info(message);
        return SUCCESS;
    }
    
    @Override
    public long getProcessCpuTime() {
        if(isSunBean){
            return sunBean.getProcessCpuTime();
        }else{
            return -1;
        }
    }
    
    @Override
    public int getFreePhysicalMemoryInPercent() {
        if(isSunBean){
            return (int) (100 * sunBean.getFreePhysicalMemorySize() / totalPhysicalMemorySize);
        }else{
            return -1;
        }
    }

    @Override
    public int getFreeSwapSpaceSizeInPercent() {
        if(isSunBean){
            return (int) (100 * sunBean.getFreePhysicalMemorySize() / totalSwapSpaceSize);
        }else{
            return -1;
        }
    }

    @Override
    public double getSystemLoadAverage() {
        return bean.getSystemLoadAverage();
    }

    @Override
    public boolean isSunBean(){
        return this.isSunBean;
    }
}
